package com.nh.glory.ware.security.authentication;

import com.nh.glory.ware.security.authentication.jwt.JwtToken;
import com.nh.glory.ware.security.model.LoginUserDetails;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

public class StatelessAuthenticationToken extends AbstractAuthenticationToken {

    private JwtToken token;
    private LoginUserDetails userDetails;

    public StatelessAuthenticationToken(JwtToken unsafeToken) {
        super(null);
        this.token = unsafeToken;
        this.setAuthenticated(false);
    }

    public StatelessAuthenticationToken(LoginUserDetails userDetails, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.eraseCredentials();
        this.userDetails = userDetails;
        super.setAuthenticated(true);
    }

    @Override
    public void setAuthenticated(boolean authenticated) {
        if (authenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return token;
    }

    @Override
    public Object getPrincipal() {
        return this.userDetails;
    }

    @Override
    public void eraseCredentials() {        
        super.eraseCredentials();
        this.token = null;
    }

}
